<?php
namespace app\api\logic;
use app\common\model\Cart;
use app\common\model\UserCollect;
use app\common\model\ShopConfig;
use app\common\server\UrlServer;
use think\Db;

class ArticleLogic
{
   public static function lists($user_id,$get,$page,$size)
    {
        $where[] = [
            ['a.delete_time', '=', 0],
            ['a.is_show', '=', 1]
        ];

        if (!empty($get['cid'])) {
            $where[] = ['cid', '=',$get['cid']];
        }
        $order = [];
        if($get['sort']==1){
            $order['id'] = 'desc';
        }else{
            $order['likes'] = 'desc';
        }
        $res = DB::name('article')->alias('a')
            ->where($where)
            ->field('a.id,a.title,a.synopsis,a.image,a.visit,a.likes,a.create_time')
            ->order(['a.id' => 'desc']);

        $count = $res->count();
        $article = $res->page($page, $size)->select();
        $img_url=ShopConfig::get('website', 'img_url');
        $company_name = ShopConfig::get('website', 'company_name');
        $company_logo = ShopConfig::get('website', 'company_logo');
        foreach ($article as &$item) {
            $item['create_time'] = date('Y-m-d', $item['create_time']);
            $item['image'] = UrlServer::getFileUrl($item['image']);
            $item['company_name'] = $company_name;
            $item['company_logo'] = $company_logo;
        }
        $more = is_more($count,$page,$size);  //是否有下一页
        $data = [
            'list'          => $article,
            'page_no'       => $page,
            'page_size'     => $size,
            'count'         => $count,
            'more'          => $more
        ];
        return $data;
    }


     public static function getArticleDetail($user_id,$get)
    {
        DB::name('article')
            ->where(['id' => $get['id'], 'delete_time' => 0])
            ->setInc('visit');

        $res = DB::name('article')
            ->where(['delete_time' => 0, 'id' => $get['id']])
            ->field('id,title,image,visit,create_time,content,likes')
            ->order(['create_time' => 'desc'])
            ->find();

        $preg = '/<img.*?src="((?!(https|http)).*?)".*?\/?>/i';
        $local_url = UrlServer::getFileUrl();
        $res['content'] = preg_replace($preg, '<img src="' . $local_url . '${1}" />', $res['content']);
        $res['create_time'] = date('Y-m-d ', $res['create_time']);
        return $res;
    }


     public static function getPolicyAgreementDetail($id)
    {
        $res = DB::name('policy_agreement')
            ->where(['delete_time' => 0, 'id' => $id])
            ->field('id,title,image,content,create_time')
            ->find();

        $preg = '/<img.*?src="((?!(https|http)).*?)".*?\/?>/i';
        $local_url = UrlServer::getFileUrl();
        $res['content'] = preg_replace($preg, '<img src="' . $local_url . '${1}" />', $res['content']);
        $res['create_time'] = date('Y-m-d ', $res['create_time']);
        return $res;
    }
}